<template>
  <div>

    <div class="card" style="margin-bottom: 5px;">
      <el-input v-model="data.name" style="width: 300px; margin-right: 10px" placeholder="请输入宠物品种查询"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div style="margin-bottom: 10px" v-if="data.user.role === 'ADMIN'"  >
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="pet in data.tableData" :key="pet.id">
          <el-card shadow="hover">
            <h3>{{ pet.name }}</h3>
            <p><strong>救援介绍:</strong> {{ pet.content }}</p>
            <p><strong>救援积分:</strong> {{ pet.score }}</p>
            <p><strong>志愿者负责人:</strong> {{ pet.volunteerName }}</p>
            <p><strong>所需人数:</strong> {{ pet.num }}</p>
            <p><strong>救援时间:</strong> {{ pet.time }}</p>
            <p><strong>救援地点:</strong> {{ pet.location }}</p>
            <p><strong>负责组织:</strong> {{ pet.cityName }}</p>
            <p><strong>已选人数:</strong> {{ pet.alreadyNum }}</p>
            <div style="text-align: center;"  >
              <el-button type="primary" @click="handleEdit(pet)" v-if="data.user.role !== 'USER'"  >编辑</el-button>
              <el-button type="danger" @click="handleDelete(pet.id)" v-if="data.user.role !== 'USER'"  >删除</el-button>
              <el-button type="primary" @click="choiceCourse(pet)" v-if="data.user.role === 'USER'" :disabled="(pet.num === pet.alreadyNum)" >援助</el-button>

            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="card">
      <el-pagination background layout="prev, pager, next" v-model:page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" @current-change="changePage"/>
    </div>

    <el-dialog title="信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="宠物品种" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item  label="救援介绍" prop="name">
          <el-input  v-model="data.form.content" type="textarea"
                     :rows="4" autocomplete="off"  />
        </el-form-item>
        <el-form-item label="救援积分" prop="name">
          <el-input v-model="data.form.score" autocomplete="off" />
        </el-form-item>
        <el-form-item label="志愿者负责人" prop="volunteerId">
          <el-select
              v-model="data.form.volunteerId"
              placeholder="请选择志愿者"
              size="large"
              style="width: 100%"
          >
            <el-option
                v-for="item in data.volunteerDate"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所需人数" prop="name">
          <el-input v-model="data.form.num" autocomplete="off" />
        </el-form-item><el-form-item label="救援时间" prop="name">
        <el-input v-model="data.form.time" autocomplete="off" />
      </el-form-item><el-form-item label="救援地点" prop="location">
        <el-input v-model="data.form.location" autocomplete="off" />
      </el-form-item>

          <el-form-item label="所属组织" prop="city">
            <el-select
                v-model="data.form.cityId"
                placeholder="请选择组织"
                size="large"
                style="width: 100%"
            >
              <el-option
                  v-for="item in data.cityDate"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>

      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "@/utils/request";
import {reactive} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";

const data = reactive({
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
  pageNum: 1,
  pageSize: 4,
  total: 0,
  formVisible: false,
  form: {},
  tableData: [],
  name:null,
  cityDate:[],
  volunteerDate:[],
})

// 分页查询
const load = () => {
  let volunteerId=null
  if(data.user.role==='VOLUNTEER'){
    volunteerId=data.user.id
  }

  request.get('/help/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      volunteerId:volunteerId,
    }
  }).then(res => {
    data.tableData = res.data?.list
    data.total = res.data?.total
  })
}

const changePage = (pageNum) => {
  data.pageNum =pageNum
  load()
}
// 新增
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 新增保存
const add = () => {
  request.post('/help/add', data.form).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 编辑保存
const update = () => {
  request.put('/help/update', data.form).then(res => {
    if (res.code === '200') {
      load()
      ElMessage.success('操作成功')
      data.formVisible = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 弹窗保存
const save = () => {
  // data.form有id就是更新，没有就是新增
  data.form.id ? update() : add()
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/help/deleteById/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {})
}

// 重置
const reset = () => {
  data.name = null
  load()
}

const loadCity =() =>{
  request.get('/city/selectAll').then(res=>{
    if (res.code === '200') {
      data.cityDate = res.data
    }else{
      ElMessage.error(res.msg)
    }

  })
}

const loadVolunteer =() =>{
  request.get('/volunteer/selectAll').then(res=>{
    if (res.code === '200') {
      data.volunteerDate = res.data
    }else{
      ElMessage.error(res.msg)
    }

  })
}

const choiceCourse = (row)=>{
  let helpData =JSON.parse(JSON.stringify(row))
  helpData.userId=data.user.id
  request.post('/helper/add',helpData).then(res=>{
    if(res.code==='200'){
      load()
      ElMessage.success('选择援助成功')
    }else{
      ElMessage.error(res.msg)
    }
  })
}

loadVolunteer()
loadCity()
load()
</script>